package activities;

import helper.HttpHelper;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.matchcalendar.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;

public class GoogleMapActivity extends Activity {
    private GoogleMap gMap;
    private EditText editTextSearchAddress;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_googlemap);
        findView();
        setListenerOrAdapter();
        initMap();
    }
    
    private void initMap() {	
    	gMap.setMyLocationEnabled(true);
        gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(25.106119, 121.560974), 10));
        gMap.setOnMyLocationChangeListener(new loChangeListener());
	}
    
    private class loChangeListener implements OnMyLocationChangeListener {
    	private boolean haveGetLocation = false;

		@Override
		public void onMyLocationChange(Location location) {
			if (!haveGetLocation) {
				LatLng pos = new LatLng(location.getLatitude(), location.getLongitude());
				
				gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(pos, 16));
				haveGetLocation = true;
			}
		}
    }

	private void findView() {
    	gMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.gMap)).getMap();
    	editTextSearchAddress = (EditText)findViewById(R.id.editTextSearchAddress);
	}
	
	private void setListenerOrAdapter() {
		editTextSearchAddress.setOnTouchListener(new EditTextSearchAddressTouchListener());
		gMap.setOnInfoWindowClickListener(new GMapInfoWindowClickListener());
		editTextSearchAddress.setOnEditorActionListener(new EditTextSearchAddressEditorActionListener());
	}
	
	private class EditTextSearchAddressTouchListener implements EditText.OnTouchListener {
		private boolean isTouched = false;

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (!isTouched) {
				editTextSearchAddress.setText("");
				isTouched = true;
			}
			return false;
		}
	}
	
	private class EditTextSearchAddressEditorActionListener implements EditText.OnEditorActionListener {

		@Override
		public boolean onEditorAction(TextView text, int arg1, KeyEvent arg2) {
			String searchAddress = text.getText().toString();
			
			new GetLocationRequest().execute(searchAddress);
			return false;
		}
		
		private class GetLocationRequest extends AsyncTask<String, Void, String> {
			ProgressDialog proDialog;
			
			@Override
			protected void onPreExecute() {
				proDialog = ProgressDialog.show(GoogleMapActivity.this, "正在搜尋", "正在搜尋此地點...");
			}

			@Override
			protected String doInBackground(String... params) {
				String result = null;
				
				try {
					HttpResponse resp = HttpHelper.executePost(
							"http://maps.googleapis.com/maps/api/geocode/json?address=" + params[0] + "&sensor=false&language=zh-TW");
					
					result = EntityUtils.toString(resp.getEntity());
				} catch (ParseException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return result;
			}
			
			@Override
			protected void onPostExecute(String result) {
				try {
					JSONObject jsonObj = new JSONObject(result);
					
					proDialog.cancel();
					gMap.clear();
					if (jsonObj.getString("status").equals("ZERO_RESULTS")) {
						new AlertDialog.Builder(GoogleMapActivity.this)
						.setTitle("找不到此地點")
						.setMessage("搜尋不到您要找的地方喔")
						.setPositiveButton(android.R.string.ok, null)
						.show();
					}
					else {
						JSONArray jsonArrResult = jsonObj.getJSONArray("results");
						
						for (int i=0; i<jsonArrResult.length(); i++) {
							JSONObject jsonObjResult = jsonArrResult.getJSONObject(i);
							String posName = jsonObjResult.getJSONArray("address_components")
									.getJSONObject(0).getString("long_name");
							String posAddr = jsonObjResult.getString("formatted_address");
							JSONObject jsonLocation = jsonObjResult
									.getJSONObject("geometry").getJSONObject("location");
							LatLng focusPos = new LatLng(
									jsonLocation.getDouble("lat"), jsonLocation.getDouble("lng"));
							Marker marker = gMap.addMarker(
									new MarkerOptions().position(focusPos).title(posName).snippet(posAddr));
							
							if (i == 0) {
								marker.showInfoWindow();
								gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(focusPos, 16));
							}
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	private class GMapInfoWindowClickListener implements GoogleMap.OnInfoWindowClickListener {

		@Override
		public void onInfoWindowClick(Marker marker) {
			Bundle bundle = new Bundle();
			Intent intent = new Intent();
			
			bundle.putString("activityAddr", marker.getSnippet());
			intent.putExtras(bundle);
			setResult(RESULT_OK, intent);
			GoogleMapActivity.this.finish();
		}
	}
}